#include <CODEPORTS/codeports.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
	BOX box;
} Fire;

void
DEMO_Init(DEMO *demo, BOX *box)
{
	Fire *fire;
	demo->box = box;
	demo->data = malloc(sizeof(Fire));
	fire = demo->data;
	BOX_Allocate(&fire->box, box->info.width, box->info.height);
	BOX_Clear(&fire->box);
}

void
DEMO_Frame(DEMO *demo)
{
	Fire *fire = demo->data;
	float x, y;
	unsigned char r[5], g[5], b[5];
	for(x = 0; x < fire->box.info.width; x += 1.0f)
	{
		r[0] = abs(32768 + rand()) % 256;
		g[0] = abs(32768 + rand()) % 256 / 4;
		b[0] = abs(32768 + rand()) % 256 / 16;
		BOX_SetPixelRGB(&fire->box, x, fire->box.info.height - 1, r[0], g[0], b[0]);
		BOX_SetPixelRGB(demo->box, x, fire->box.info.height - 1, r[0], g[0], b[0]);
	}
	for(x = 0; x < fire->box.info.width; x += 1.0f)
	{
		for(y = 0; y < fire->box.info.height; y += 1.0f)
		{
			BOX_GetPixelRGB(&fire->box, ((unsigned int) x - 1 + fire->box.info.width) % fire->box.info.width, ((unsigned int) y + 1) % fire->box.info.height, &r[1], &g[1], &b[1]);
			BOX_GetPixelRGB(&fire->box, ((unsigned int) x + 0) % fire->box.info.width, ((unsigned int) y + 1) % fire->box.info.height, &r[2], &g[2], &b[2]);
			BOX_GetPixelRGB(&fire->box, ((unsigned int) x + 1) % fire->box.info.width, ((unsigned int) y + 1) % fire->box.info.height, &r[3], &g[3], &b[3]);
			BOX_GetPixelRGB(&fire->box, ((unsigned int) x + 0) % fire->box.info.width, ((unsigned int) y + 2) % fire->box.info.height, &r[4], &g[4], &b[4]);
			r[0] = ((r[1] + r[2] + r[3] + r[4]) * 32) / 129;
			g[0] = ((g[1] + g[2] + g[3] + g[4]) * 32) / 129;
			b[0] = ((b[1] + b[2] + b[3] + b[4]) * 32) / 129;
			BOX_SetPixelRGB(&fire->box, x, y, r[0], g[0], b[0]);
			BOX_SetPixelRGB(demo->box, x, y, r[0], g[0], b[0]);
		}
	}
}

void
DEMO_Final(DEMO *demo)
{
	Fire *fire = demo->data;
	BOX_Free(&fire->box);
	free(demo->data);
}
